package net.diaowen.dwsurvey.dao.impl;


import net.diaowen.common.QuType;
import net.diaowen.common.dao.BaseDaoImpl;
import net.diaowen.common.enums.DataStatusEnum;
import net.diaowen.common.plugs.page.Page;
import net.diaowen.dwsurvey.dao.QuExcelTemplateDao;
import net.diaowen.dwsurvey.dao.QuestionDao;
import net.diaowen.dwsurvey.entity.*;
import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * excel模板
 *
 * @author 王骏(wondream322 @ gmail.com)
 */

//@Repository("questionDao")
@Repository
public class QuExcelTemplateDaoImpl extends BaseDaoImpl<QuExcelTemplate, String> implements QuExcelTemplateDao {

    public List<QuExcelTemplate> findByQuId(String quId) {
        Page<QuExcelTemplate> page = new Page<QuExcelTemplate>();
        page.setOrderBy("orderById");
        page.setOrderDir("asc");

        CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
        CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(QuExcelTemplate.class);
        Root root = criteriaQuery.from(QuExcelTemplate.class);
        criteriaQuery.select(root);
        Predicate eqQuId = criteriaBuilder.equal(root.get("quId"), quId);
        Predicate eqvisibility = criteriaBuilder.equal(root.get("state"), DataStatusEnum.VALID.getValue());
        criteriaQuery.where(eqQuId, eqvisibility);
        return findAll(criteriaQuery);
    }

    public void update(QuExcelTemplate entity) {
        super.save(entity);
    }

    /**
     * 保存题目DAO入口
     */
    @Override
    public void save(QuExcelTemplate entity) {
        if (entity == null) {
            return;
        }
        Criterion criterion = Restrictions.eq("quId", entity.getQuId());
        QuExcelTemplate quExcelTemplate = this.findFirst("createTime", false, criterion);
        if (quExcelTemplate == null) {
            Session session = getSession();
            session.save(entity);
            return;
        }
        try {
            String id = quExcelTemplate.getId();
            BeanUtils.copyProperties(quExcelTemplate, entity);
            quExcelTemplate.setId(id);
            update(quExcelTemplate);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
